﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Tian.Common.Enums.HttpEnum;

namespace Tian.Common.Https
{
    /// <summary>
    /// 请求类封装
    /// </summary>
    public static class RequestUtil
    {
        #region 创建访问
        /// <summary>
        /// 模拟http请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="type">请求方式</param>
        /// <param name="dic">参数字典</param>
        /// <returns></returns>
        public static string RequestMethod(string url, RequestMothed type, Dictionary<string, object> dic)
        {
            //爆400错误有可能是跨域问题，先解决跨域，在看看是不是其他情况
            string result = "";
            HttpWebRequest req = null;
            HttpWebResponse resp = null;
            switch (type)
            {
                case RequestMothed.Get:
                    req = (HttpWebRequest)WebRequest.Create(url + '?' + BuildParams(dic));
                    req.ContentType = "application/json;charset=utf-8";
                    req.Method = "get";
                    resp = GetMothed(req);
                    break;
                case RequestMothed.Post:
                    req = (HttpWebRequest)WebRequest.Create(url);
                    req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                    req.Method = "post";
                    resp = PostMothed(req, dic);
                    break;

                case RequestMothed.Put:
                    req = (HttpWebRequest)WebRequest.Create(url);
                    req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                    req.Method = "put";
                    resp = PutMothed(req, dic);
                    break;
                case RequestMothed.Delete:
                    req = (HttpWebRequest)WebRequest.Create(url);
                    req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                    req.Method = "delete";
                    resp = DeleteMothed(req, dic);
                    break;
            }
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }
        /// <summary>
        /// 模拟http请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="type">请求方式</param>
        /// <param name="t">额外对象参数</param>
        /// <returns></returns>
        public static string RequestMethod<T>(string url, string type, T t) where T : class
        {
            //爆400错误有可能是跨域问题，先解决跨域，在看看是不是其他情况
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = type;
            req.ContentType = "application/json;charset=utf-8";
            #region 添加Post 参数
            string json = JsonConvert.SerializeObject(t);
            byte[] data = Encoding.UTF8.GetBytes(json);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="data">二进制流</param>
        /// <param name="urlBoundary">分隔边界</param>
        /// <returns></returns>
        public static string RequestFile(string url, byte[] data, string urlBoundary)
        {
            //爆400错误有可能是跨域问题，先解决跨域，在看看是不是其他情况
            string result = "";
            HttpWebRequest req = null;
            HttpWebResponse resp = null;

            req = (HttpWebRequest)WebRequest.Create(url);
            req.ContentType = "multipart/form-data; boundary=" + urlBoundary;
            req.Method = "post";
            resp = UpFileMothed(req, data);
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;

        }
        #endregion

        #region 访问方法
        private static HttpWebResponse PostMothed(HttpWebRequest req, Dictionary<string, object> dic)
        {
            HttpWebResponse resp = null;
            try
            {
                string json = BuildParams(dic);
                byte[] data = Encoding.UTF8.GetBytes(json);
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                resp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException ex)
            {
                resp = (HttpWebResponse)ex.Response;
            }
            return resp;
        }
        private static HttpWebResponse GetMothed(HttpWebRequest req)
        {
            HttpWebResponse resp = null;
            try
            {
                resp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException ex)
            {
                resp = (HttpWebResponse)ex.Response;
            }
            return resp;
        }

        private static HttpWebResponse PutMothed(HttpWebRequest req, Dictionary<string, object> dic)
        {
            HttpWebResponse resp = null;
            try
            {
                string json = BuildParams(dic);
                byte[] data = Encoding.UTF8.GetBytes(json);
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                resp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException ex)
            {
                resp = (HttpWebResponse)ex.Response;
            }
            return resp;
        }

        private static HttpWebResponse DeleteMothed(HttpWebRequest req, Dictionary<string, object> dic)
        {
            HttpWebResponse resp = null;
            try
            {
                string json = BuildParams(dic);
                byte[] data = Encoding.UTF8.GetBytes(json);
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                resp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException ex)
            {
                resp = (HttpWebResponse)ex.Response;
            }
            return resp;
        }

        private static HttpWebResponse UpFileMothed(HttpWebRequest req, byte[] data)
        {
            HttpWebResponse resp = null;
            try
            {
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                resp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException ex)
            {
                resp = (HttpWebResponse)ex.Response;
            }
            return resp;
        }
        #endregion

        #region 参数构建
        private static string BuildParams(Dictionary<string, object> dic)
        {
            StringBuilder postData = new StringBuilder();
            foreach (var item in dic)
            {
                if (postData.ToString() != "")
                {
                    postData.Append("&");
                }
                postData.Append(item.Key + "=");
                if (item.Value.GetType() == typeof(string) || item.Value.GetType() == typeof(int))
                {
                    postData.Append(System.Web.HttpUtility.UrlEncode(item.Value.ToString()));
                }
                else
                {
                    string json = JsonConvert.SerializeObject(item.Value);
                    postData.Append(System.Web.HttpUtility.UrlEncode(json));
                }

            }
            return postData.ToString();
        }
        #endregion

        #region 公共方法
        #endregion
    }
}
